package com.lzy.cloud.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzy.cloud.order.constants.CommonConstants;
import com.lzy.cloud.order.constants.OrderBusiConstants;
import com.lzy.cloud.order.constants.OrderDistributePrefix;
import com.lzy.cloud.order.dos.OrderActionDO;
import com.lzy.cloud.order.dos.OrderActions;
import com.lzy.cloud.order.dos.OrderStatusReturnDO;
import com.lzy.cloud.order.dtos.OrderInfoDto;
import com.lzy.cloud.order.dtos.pay.OrderPayDto;
import com.lzy.cloud.order.dtos.pay.OrderPayParamsDto;
import com.lzy.cloud.order.entity.OrderInfo;
import com.lzy.cloud.order.entity.OrderPayLog;
import com.lzy.cloud.order.entity.OrderStatusHistory;
import com.lzy.cloud.order.mapper.OrderInfoMapperExt;
import com.lzy.cloud.order.mapper.OrderPayLogMapperExt;
import com.lzy.cloud.order.mapper.OrderStatusHistoryMapperExt;
import com.lzy.cloud.order.service.OrderInfoService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.exceptions.XBusinessException;
import com.lzy.framework.core.lock.RedisGlobalLock;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.tools.commons.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 订单总表底层业务
 * @Author: gyl
 * @Date: 2018/7/10 16:42
 */
@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    @Autowired
    private OrderInfoMapperExt orderInfoMapperExt;

    @Autowired
    private OrderStatusHistoryMapperExt orderStatusHistoryMapperExt;

    @Autowired
    private OrderPayLogMapperExt orderPayLogMapperExt;

    @Autowired
    private RedisGlobalLock redisGlobalLock;

    @Override
    public PageInfo<OrderInfoDto> queryList(Pager pager, OrderInfoDto orderInfoDto) {
        if (pager != null)
            PageHelper.startPage(pager.getPageNum(), pager.getPageSize());
        List<OrderInfoDto> list = orderInfoMapperExt.queryList(DozerUtils.map(orderInfoDto, OrderInfo.class));

        // 设置类型名称
        for (OrderInfoDto dto : list) {
            setTypeName(dto);
        }
        return new PageInfo<>(list);
    }

    @Override
    public OrderInfoDto find(String orderId) {
        OrderInfo orderInfo = orderInfoMapperExt.selectByPrimaryKey(orderId);
        return DozerUtils.map(orderInfo, OrderInfoDto.class);
    }

    @Override
    public OrderPayDto findToPay(String orderId) {
        return orderInfoMapperExt.findToPay(orderId);
    }

    @Override
    public boolean create(OrderInfoDto orderInfoDto) {
        return orderInfoMapperExt.insertSelective(DozerUtils.map(orderInfoDto, OrderInfo.class)) > 0;
    }

    @Override
    public boolean update(OrderInfoDto orderInfoDto) {
        return orderInfoMapperExt.updateByPrimaryKeySelective(DozerUtils.map(orderInfoDto, OrderInfo.class)) > 0;
    }

    @Override
    public Boolean updateFromPay(OrderPayParamsDto orderPayParamsDto) {
        // 更新订单状态 ：支付完成
        String key = OrderDistributePrefix.ORDER_ID + orderPayParamsDto.getOrderId();
        if (redisGlobalLock.lock(key, 3000, TimeUnit.MILLISECONDS)) {
            try {
                OrderStatusReturnDO osrd = orderInfoMapperExt.selectByOrderId(orderPayParamsDto.getOrderId(),
                        null);
                Ensure.that(osrd != null).isTrue("08000009");
                // 判断订单状态，防止重复提交
                if (osrd.getOnline().equals(CommonConstants.PayWayOrder.IS_ONLINE)) {// 线上支付
                    Ensure.that(osrd.getMinStatus().equals(CommonConstants.Status.ZERO)).isTrue("08000029");
                    // 更新订单状态,记录订单状态记录
                    OrderActionDO oaDO = new OrderActionDO();
                    oaDO.setOperateName(orderPayParamsDto.getPayName());
                    oaDO.setOrderId(orderPayParamsDto.getOrderId());
                    oaDO.setMoneyPaid(osrd.getOrderAmount());
                    oaDO.setPayTime(new Date());
                    oaDO.setPayWay(orderPayParamsDto.getPayId());
                    oaDO.setStopPayTime(null);
                    //分利的金额
//                            BigDecimal money = null;
//                            switch (osrd.getType() + "") {
//                                case CommonConstants.Biz.TOUR_CAR_SALE: {
//                                    oaDO.setRefund(CommonConstants.RefundStatus.NOREFUND);
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.CONTACT));
//                                    oaDO.setCustomerMethod("");
//                                    oaDO.setOsde(OrderStatusDesEnum.TOURCARSALE_YES_PAY);
//                                    money = osrd.getItemAmount();
//                                    break;
//                                }
//                                case CommonConstants.Biz.TOUR_CAR_RENT: {
//                                    oaDO.setCarStatus(OrderStatusDesEnum.TOURCARRENT_NOT_CAR.getStatus());//待提车
//                                    oaDO.setRefund(CommonConstants.RefundStatus.NOREFUND);//
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.PICKCAR));
//                                    oaDO.setCustomerMethod(OrderActionConstants.getStr(OrderActionConstants.APPEAL,
//                                            OrderActionConstants.RETREAT));
//                                    oaDO.setOsde(OrderStatusDesEnum.TOURCARRENT_NO_GOODS);
//                                    OrderMoney om = orderMoneyMapperExt.selectByOrderId(orderPayParamsDto.getOrderId());
//                                    money = BigDecimalUtil.subtract(om.getItemAmount(), om.getCoupon());
//                                    break;
//                                }
//                                case CommonConstants.Biz.CAMP: {
//                                    oaDO.setRefund(RefundStatus.NOREFUND);//
//                                    oaDO.setOsde(OrderSatusDesEnum.CAMPSITE_NO_GOODS);
//                                    oaDO.setShopMethod("");
//                                    oaDO.setCustomerMethod(OrderActionConstants.getStr(OrderActionConstants.APPEAL, OrderActionConstants.RETREAT));
//                                    // 判断如果是当天12点后的单子，则直接跳转为出行中
//                                    String sourceStartDate = DateUtil.getDateStringY(sor.getSendTime());
//                                    if (StringUtil.isNotBlank(sourceStartDate) && java.time.LocalDate.parse(sourceStartDate).isEqual(java.time.LocalDate.now())
//                                            && LocalDateTime.now().getHour() >= 12) {
//                                        // 出行中
//                                        oaDO.setOsde(OrderSatusDesEnum.CAMPSITE_YES_GOODS);
//                                        oaDO.setCustomerMethod(OrderActionConstants.getStr(OrderActionConstants.APPEAL));
//                                    }
//                                    money = osrd.getItemAmount();
//                                    break;
//                                }
//                                case CommonConstants.Biz.OUTDOOR: {
//                                    oaDO.setRefund(RefundStatus.APPLYREFUND);// 付款之后，显示售后等信息
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.SEND));
//                                    oaDO.setCustomerMethod(OrderActionConstants.getStr(OrderActionConstants.APPEAL));
//                                    oaDO.setOsde(OrderSatusDesEnum.OUTDOOR_NO_GOODS);
//                                    money = osrd.getItemAmount();
//                                    break;
//                                }
//                                case CommonConstants.Biz.LINE: {
//                                    oaDO.setRefund(RefundStatus.NOREFUND);//
//                                    oaDO.setOsde(OrderSatusDesEnum.JOURNEY_NO_GOODS);
//                                    oaDO.setShopMethod("");
//                                    oaDO.setCustomerMethod("");
//                                    money = osrd.getItemAmount();
//                                    // 判断如果是当天12点后的单子，则直接跳转为出行中
//                                    String sourceStartDate = DateUtil.getDateStringY(sor.getSendTime());
//                                    if (StringUtil.isNotBlank(sourceStartDate) && java.time.LocalDate.parse(sourceStartDate).isEqual(java.time.LocalDate.now())
//                                            && LocalDateTime.now().getHour() >= 12) {
//                                        // 出行中
//                                        oaDO.setOsde(OrderSatusDesEnum.JOURNEY_YES_GOODS);
//                                    }
//                                    break;
//                                }
//                                case CommonConstants.Biz.PLAY: {
//                                    oaDO.setOsde(OrderSatusDesEnum.PLAY_NO_GOODS);
//                                    oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.CHECKCODE));
//                                    oaDO.setCustomerMethod(OrderActionConstants.getStr(OrderActionConstants.RETREAT));
//                                    money = osrd.getItemAmount();
//                                    break;
//                                }
//                                case CommonConstants.Biz.MOTOR_COUPON: {
//                                    oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setOsde(OrderSatusDesEnum.MOTOR_COUPON_COMPLETE);
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.CHECKCODE));
//                                    oaDO.setCustomerMethod("");
//                                    break;
//                                }
//                                case CommonConstants.Biz.DREAM_PLAN: {
//                                    oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setOsde(OrderSatusDesEnum.DREAM_PLAN_COMPLETE);
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.CHECKCODE));
//                                    oaDO.setCustomerMethod("");
//                                    break;
//                                }
//                                case CommonConstants.Biz.QUEEN_PLAN: {
//                                    oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setOsde(OrderSatusDesEnum.QUEEN_PLAN_COMPLETE);
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.CHECKCODE));
//                                    oaDO.setCustomerMethod("");
//                                    break;
//                                }
//                                case CommonConstants.Biz.GUIDE: {
//                                    // 支付成功以后待确认
//                                    oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setOsde(OrderSatusDesEnum.GUIDE_NO_CONFIRM);
//                                    // 显示确认按钮
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.DATE_CONFIRM));
//                                    oaDO.setCustomerMethod(OrderActionConstants.getStr(OrderActionConstants.RETREAT));
//                                    money = osrd.getItemAmount();
//                                    break;
//                                }
//                                case CommonConstants.Biz.PROMOTION: {
//                                    // 支付成功以后待使用
//                                    oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setOsde(OrderSatusDesEnum.PROMOTION_NO_GOODS);
//                                    // 显示手动完结按钮
//                                    oaDO.setShopMethod(OrderActionConstants.getStr(OrderActionConstants.MANUAL_COMPLETE));
//                                    oaDO.setCustomerMethod(OrderActionConstants.getStr(""));
//                                    oaDO.setAdminMethod(OrderActionConstants.getStr(""));
//                                    money = osrd.getItemAmount();
//                                    break;
//                                }
//                                /*case Biz.AGENT_PRODUCT: {
//                                    *//*oaDO.setRefund(RefundStatus.NOREFUND);
//                                    oaDO.setOsde(OrderSatusDesEnum.AGENT_PRODUCT_YES_GOODS);*//*
//                                    break;
//                                }*/
//                                default: {
//                                    break;
//                                }
//                            }

                    oaDO.setMaxStatus(CommonConstants.OrderBigStatus.VALID_ORDER);
                    oaDO.setPayStatus(CommonConstants.Status.ONE);
                    oaDO.setGoodStatus(CommonConstants.Status.ZERO);
                    Boolean v = updateStatus(oaDO);
                    Ensure.that(v).isTrue("08000019");

                    OrderPayLog orderTransPay = new OrderPayLog();
                    orderTransPay.setId(IdWorker.getInstance().nextId());
                    orderTransPay.setMoney(osrd.getOrderAmount());
                    orderTransPay.setOrderId(orderPayParamsDto.getOrderId());
                    orderTransPay.setStatus(OrderBusiConstants.PayStatusEnum.YESPAY.getK());
                    orderTransPay.setThirdWay(orderPayParamsDto.getPayName());
                    orderTransPay.setMemberId(osrd.getMemberId());
                    orderTransPay.setThirdId(orderPayParamsDto.getPayId());
                    orderPayLogMapperExt.insertSelective(orderTransPay);
                    // 添加 房车销售以及商城除外

//                            if (CommonConstants.Biz.OUTDOOR.equals(osrd.getType() + "")) {
//
//                            } else if (CommonConstants.Biz.MOTOR_COUPON.equals(osrd.getType() + "")) {
//
//                            } else if (CommonConstants.Biz.DREAM_PLAN.equals(osrd.getType() + "")) {
//
//                            } else if (CommonConstants.Biz.QUEEN_PLAN.equals(osrd.getType() + "")) {
//
//                            } else if (CommonConstants.Biz.TOUR_CAR_SALE.equals(osrd.getType() + "")) {
//                                insertOrderJobStatus(osrd.getOrderId(), osrd.getItemAmount(), osrd.getItemAmount(), new Date(), osrd.getType());
//                            } else if (CommonConstants.Biz.AGENT_PRODUCT.equals(osrd.getType() + "")) {
//
//                            } else {
//                                insertOrderJobStatus(osrd.getOrderId(), osrd.getItemAmount(), money, osrd.getEndTime(), osrd.getType());
//                            }

                    // 发送短信 todo
//                            OrderMessageDTO dto = new OrderMessageDTO();
//                            dto.setOrderId(orderPayParamsDto.getOrderId());
//                            dto.setMinStatus(oaDO.getOsde().getStatus());
//                            orderMsgApi.sendMessage(dto);
//                            kvClient.addQueue(OrderDistributePrefix.QueueOrder.QUEUE_ORDER_MESSAGE, dto);
//                            LOGGER.error("支付完成加入消息队列成功，订单号："+osrd.getOrderId());
                    //服务费
//                            if(!BigDecimalUtil.isZeroOrNull(osrd.getPlatformFee())){
//                                MsgOrderProfitDTO mopfDTO = new MsgOrderProfitDTO();
//                                mopfDTO.setIsIntegral(0);
//                                mopfDTO.setIsPlatformFee(1);
//                                mopfDTO.setOrderId(osrd.getOrderId());
//                                mopfDTO.setMoney(osrd.getPlatformFee());
//                                mopfDTO.setType(osrd.getType());
//                                kvClient.addQueue(OrderDistributePrefix.QueueOrder.QUEUE_ORDER_PROFIT, mopfDTO);
//                                LOGGER.info("添加订单分利队列(平台服务费)====成功====订单号:{},分利的金额:{}元,操作日期:{}", osrd.getOrderId(), osrd.getPlatformFee(), new Date());
//                            }
//                    String key = OrderDistributePrefix.ActionOrder.CANCLE + orderPayParamsDto.getOrderId();
                    // 如果成功，需要添加标识：给定时任务做标记
//                            kvClient.save(key, CommonConstants.ActionFlag.NO, Integer.MAX_VALUE);
                } else {
                    // 线下支付
                    Ensure.that(true).isTrue("08000001");
                }
                return Boolean.TRUE;
            } catch (XBusinessException e) {
                throw e;
            } finally {
                redisGlobalLock.unlock(key);
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean updateFromRefund(OrderPayParamsDto orderPayParamsDto) {
        return null;
    }

    @Override
    public Boolean updateStatus(OrderActionDO oaDO) {
        OrderActions oa = OrderActions.readFromDO(oaDO);
        Integer count = orderInfoMapperExt.updateStatusByOrderId(oa);
        if (count != null && count > 0) {
            // insert数据：订单状态跟踪明细
//            if ((oaDO.getOrderId() + "").startsWith(CommonConstants.Biz.LINE)) {
//                OrderInfoCampsite oc = new OrderInfoCampsite();
//                oc.setOrderId(oaDO.getOrderId());
//                oc.setMinStatus(oaDO.getOsde().getStatus());
//                oc.setDesStatus(oaDO.getOsde().getDes());
//                orderInfoCampsiteMapperExt.updateByOrderId(oc);
//            }

            OrderStatusHistory osh = doWork(oaDO);
            if (osh == null) {
                return true;
            }
            return orderStatusHistoryMapperExt.insertSelective(osh) > 0;
        }

        return false;
    }

    /**
     * 更新主订单，同时insert历史订单状态
     *
     * @return
     */
    private OrderStatusHistory doWork(OrderActionDO oaDO) {
        if (oaDO == null) {
            return null;
        }
        if (!oaDO.getV()) {
            return null;
        }
        OrderStatusHistory result = new OrderStatusHistory();
        result.setId(IdWorker.getInstance().nextId());
        result.setOrderId(oaDO.getOrderId());
        result.setOperateId(oaDO.getOperateId());
        result.setOperateName(oaDO.getOperateName());
        if (oaDO.getOsde() != null) {
            result.setStatus(oaDO.getOsde().getStatus());
            result.setDesStatus(oaDO.getOsde().getDes());
        }
        // 如果为空，则默认为管理员
        if (null == result.getOperateId() && null == result.getOperateName()) {
            result.setOperateName("管理员");
        }
        result.setPayStatus(oaDO.getPayStatus());
        result.setGoodStatus(oaDO.getGoodStatus());
        result.setRemark(oaDO.getRemark());
        return result;
    }

    /**
     * 设置类型名称
     *
     * @param orderInfoDto
     */
    private void setTypeName(OrderInfoDto orderInfoDto) {
        switch (orderInfoDto.getType() + "") {
            case CommonConstants.Biz.TOUR_CAR_SALE: {
                orderInfoDto.setTypeName(CommonConstants.BizName.TOUR_CAR_SALE);
                break;
            }
            case CommonConstants.Biz.TOUR_CAR_RENT: {
                orderInfoDto.setTypeName(CommonConstants.BizName.TOUR_CAR_RENT);
                break;
            }
            case CommonConstants.Biz.CAMP: {
                orderInfoDto.setTypeName(CommonConstants.BizName.CAMP);
                break;
            }
            case CommonConstants.Biz.OUTDOOR: {
                orderInfoDto.setTypeName(CommonConstants.BizName.OUTDOOR);
                break;
            }
            case CommonConstants.Biz.LINE: {
                orderInfoDto.setTypeName(CommonConstants.BizName.LINE);
                break;
            }
            case CommonConstants.Biz.PLAY: {
                orderInfoDto.setTypeName(CommonConstants.BizName.PLAY);
                break;
            }
            case CommonConstants.Biz.MOTOR_COUPON: {
                orderInfoDto.setTypeName(CommonConstants.BizName.MOTOR_COUPON);
                break;
            }
            case CommonConstants.Biz.DREAM_PLAN: {
                orderInfoDto.setTypeName(CommonConstants.BizName.DREAM_PLAN);
                break;
            }
            case CommonConstants.Biz.QUEEN_PLAN: {
                orderInfoDto.setTypeName(CommonConstants.BizName.QUEEN_PLAN);
                break;
            }
            case CommonConstants.Biz.GUIDE: {
                orderInfoDto.setTypeName(CommonConstants.BizName.GUIDE);
                break;
            }
            case CommonConstants.Biz.PROMOTION: {
                orderInfoDto.setTypeName(CommonConstants.BizName.PROMOTION);
                break;
            }
            default: {
                Ensure.that(true).isFalse("08000001");
                break;
            }
        }
    }

}
